<template>
  <div class="coursemain">
    <!-- 课程的分类 -->
    <div class="course-main">
      <section class="search-container">
        <div class="search-item">
          <div class="title-name">课程方向：</div>
          <div class="all-items">
            <el-tag
              :class="
                indexObj.indexWhere === undefined
                  ? 'category-poniter'
                  : 'category-poniter category-poniter-item'
              "
              effect="plain"
              type="info"
              @clicl="buildingCondition('fcategory', null)"
            >
              全部
            </el-tag>
            <el-tag
              :class="
                indexObj.indexWhere === index
                  ? 'category-poniter'
                  : 'category-poniter category-poniter-item'
              "
              effect="plain"
              type="info"
              v-for="(item, index) in firstArr"
              :key="index"
              @click="buildingCondition('fcategory', item, index)"
            >
              {{ item.categoryName }}
            </el-tag>
          </div>
        </div>
        <div class="search-item search-item-transition" style="top: 45px">
          <div class="title-name">课程分类：</div>
          <div class="all-items">
            <el-tag
              effect="plain"
              type="info"
              :class="
                indexObj.indexType === undefined
                  ? 'category-poniter'
                  : 'category-poniter category-poniter-item'
              "
              @click="buildingCondition('scategory', null)"
            >
              全部
            </el-tag>
            <el-tag
              effect="plain"
              type="info"
              :class="
                indexObj.indexType === index
                  ? 'category-poniter'
                  : 'category-poniter category-poniter-item'
              "
              v-for="(item, index) in secondArr"
              :key="index"
              @click="buildingCondition('scategory', item, index)"
              >{{ item.categoryName }}
            </el-tag>
          </div>
        </div>
        <div class="search-item" style="top: 90px">
          <div class="title-name">课程难度：</div>
          <div class="all-items">
            <el-tag
              :class="
                indexObj.indexEasy === undefined
                  ? 'category-poniter'
                  : 'category-poniter category-poniter-item'
              "
              effect="plain"
              type="info"
              @click="buildingCondition('clevel', null)"
            >
              全部
            </el-tag>
            <el-tag
              :class="
                indexObj.indexEasy === index
                  ? 'category-poniter'
                  : 'category-poniter category-poniter-item'
              "
              effect="plain"
              type="info"
              @click="buildingCondition('clevel', item, index)"
              v-for="(item, index) in courseLevel"
              :key="index"
              >{{ item.text }}
            </el-tag>
          </div>
        </div>
      </section>
    </div>
    <!-- 课程卡片部分 -->
    <div class="main-container">
      <div class="container-top">
        <ul class="all">
          <li
            class="item"
            @click="handleZonghe"
            :class="[active == true ? 'active' : '']"
          >
            综合
          </li>
          <li class="item split">|</li>
          <li
            class="item"
            @click="handleCourse"
            :class="[active2 == true ? 'active2' : '']"
          >
            最新课程
          </li>
          <li class="item split">|</li>
          <li
            class="item"
            @click="mostBuy"
            :class="[active3 == true ? 'active3' : '']"
          >
            最多购买
          </li>
          <li class="item split">|</li>
          <li class="item item-price" @click="handlePrice">
            价格
            <span class="arrow">
              <i
                class="el-icon-caret-top"
                :style="priceSortBy == '2' ? 'color:#2c80ff' : ''"
              ></i>
              <i
                class="el-icon-caret-bottom"
                :style="priceSortBy == '1' ? 'color:#2c80ff' : ''"
              ></i>
            </span>
          </li>
        </ul>
        <ul class="right">
          <li class="right-item">
            <el-radio-group
              v-model="isFreeOrIsMember"
              @change="changeFreeOrMember"
            >
              <el-radio label="1">免费课程</el-radio>
              <el-radio label="2">会员课程</el-radio>
            </el-radio-group>
          </li>
        </ul>
      </div>
      <div class="container-body" v-if="arrcourse && arrcourse.length > 0">
        <div class="newCourseContent">
          <ul class="courseUl">
            <li
              class="courseItem"
              v-for="(item, index) in arrcourse"
              :key="index"
            >
              <div class="courseInfo">
                <router-link :to="{path:'/course-info/' + item.id}">
                  <div
                    class="memberlogo"
                    v-if="item.inMenber == 1 && item.discountPrice != 0"
                  >
                    <img src="../../assets/image/member/vipLogo.png" alt="" />
                  </div>
                  <div class="courseBg">
                    <img class="courseImg" :src="item.courseCover" alt="" />
                  </div>
                </router-link>
                <div class="courseName">{{ item.courseName }}</div>
                <div class="courseDegree">
                  {{ item.courseLevel }} ·
                  {{ item.purchaseCounter + item.purchaseCnt }} 人购买
                </div>
                <div class="coursePrice">
                  <div class="coursePriceZero" v-if="item.discountPrice">
                    <div class="pricefree">免费学习</div>
                    <img src="../../assets/image/about/free.png" alt="" />
                  </div>

                  <div class="courseMemberbg" v-else-if="item.inMember == 1">
                    <span class="price">¥ {{ item.discountPrice }}</span>
                    <span class="courseMember">会员免费</span>
                    <img src="../../assets/image/member/kings.png" alt="" />
                  </div>

                  <div class="price" v-else>¥ {{ item.salePrice }}</div>

                  <div class="addCart" @click="accCart(item)">
                    <i class="el-icon-shopping-cart-1 cart"></i>
                    <span class="cart-text">加入购物车</span>
                  </div>
                </div>
              </div>
            </li>
          </ul>
        </div>
      </div>
      <div class="container-body" v-else>
        <el-empty
          image="/image/about/course-empt.png"
          description="暂无课程"
        ></el-empty>
      </div>
      <!-- 分页器 -->
      <div class="pages">
        <pagination
          v-show="totalPage > 0"
          :total="totalPage"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
  </div>
</template>

<script>
import {
  getFirstCategorys,
  getSecondCategorys,
} from "@/common/api/courseCategory.js";
import { queryCourse } from "@/common/api/courseManage.js";
import { addShopCar } from "@/common/api/shopcar";
import { createToken } from "@/common/api/token";
import{mapState} from 'vuex'
export default {
  data() {
    return {
      firstArr: [], //一级分类
      secondArr: [], //二级分类
      queryParams: {
        pageNum: 1,
        pageSize: 12,
        total: 0,
        entity: {
          courseName: "",
          status: "",
          firstCategory: "",
          courseLevel: "",
          secondCategory: "",
          sortBy: "",
          isMember: "",
          isFree: "",
          tags: "",
        },
      },
      arrcourse: [], //课程信息
      indexObj: {
        indexWhere: undefined,
        indexType: undefined,
        indexEasy: undefined,
      },

      categorysDetail: [],
      priceSortBy: "",
      isFreeOrIsMember: "",
      degreeArr: [],
      courseLevel: [
        {
          text: "初级",
          code: "1",
        },
        {
          text: "中级",
          code: "2",
        },
        {
          text: "高级",
          code: "3",
        },
      ],
      memberId: "",
      courseId: "",
      token: "",
      tokens: "",
      selectedConditions: [],
      active: false,
      active2: false,
      active3: false,
      totalPage: 0, //分页器
    };
  },
  created() {
    // let keywords = this.$route.query.keywords
    // if(keywords){
    //   this.queryParams.entity.courseName = keywords
    // }
    this.getFirstCategorys();
    this.getSecondCategorys();
    this.queryCourse(this.queryParams);
    this.getList();
  },
  computed: {
    ...mapState({
      userInfo:(state) => state.user.userInfo
    })
  },
  watch: {
    $route:{   // 搜索监听
      immediate:true,
      handler(to,form){
        let query = to.query
        // console.log(query);
        this.queryParams.entity.courseName = query.keywords
      }
    }
  },
  methods: {
    // 获取一级分类
    getFirstCategorys() {
      getFirstCategorys().then((res) => {
        // console.log(res, '一级');
        if (res.meta.code == "200") {
          this.firstArr = res.data.list;
        }
      });
    },
    //获取二级分类
    getSecondCategorys(categoryId) {
      // 有数据传categoryId，没有就传-1
      getSecondCategorys(categoryId ? categoryId : "-1").then((res) => {
        // console.log(res,'二级');
        this.secondArr = res.data.list;
      });
    },
    // 获取课程信息
    queryCourse(queryParams) {
      queryCourse(queryParams).then((res) => {
        // console.log(res,'课程信息');
        this.arrcourse = res.data.pageInfo.list;
        this.arrcourse.forEach((item) => {
          switch (item.courseLevel) {
            case 1:
              item.courseLevel = "初级";
              break;
            case 2:
              item.courseLevel = "中级";
              break;
            case 3:
              item.courseLevel = "高级";
              break;
            default:
              item.courseLevel = "";
          }
        });
      });
    },
    // 切换分类的事件   三个按钮用一个事件，传的值不同
    buildingCondition(type, object, index) {
      // console.log(type,item,index);
      if (type == "fcategory") {
        // 这是一级
        this.indexObj.indexWhere = index; // 一级按钮样式添加
        this.indexObj.indexType = undefined; // 二级按钮取消样式
        this.indexObj.indexEasy = undefined; // 课程等级取消样式
        object = object != null ? object : -1;
        this.getSecondCategorys(object.id); // 获取二级分类
        // 修改请求课程的参数
        this.queryParams.entity.firstCategory =
          object && object.id ? object.id : "";
        this.queryParams.entity.secondCategory = ""; //
        this.queryParams.entity.courseLevel = ""; // 难度为空
        this.queryCourse(this.queryParams); // 课程方法
      } else if (type == "scategory") {
        // 这是二级课程分类
        this.indexObj.indexType = index; // 二级添加样式
        object = object != null ? object : -1; // 如果有对象就请求该对象，没有就给-1，请求所有的课
        let secondId = object.id;
        this.queryParams.entity.secondCategory =
          object && secondId ? secondId : "";
        if (this.indexObj.indexType !== undefined) {
          // 直接点击二级，给一级加样式。
          // 在一级分类的标签中查找是否有二级分类标签父级id一样的id
          let curren = this.firstArr.findIndex(
            (item) => item.id === object.parentId
          ); // 这里获取的object.parentId 是一级的id下标
          this.indexObj.indexWhere = curren; // 修改一级标签样式
          getSecondCategorys(object.parentId ? object.parentId : "-1").then(
            (res) => {
              // console.log(res,1111111);  //这里获取二级分类有哪些
              if (res.meta.code == "200") {
                this.secondArr = res.data.list;
                let secondIndex = this.secondArr.findIndex(
                  (item) => item.id === secondId
                );
                this.indexObj.indexType = secondIndex;
              }
            }
          );
          this.queryCourse(this.queryParams); //请求课程
        } else {
          this.indexObj.indexType = undefined;
        }
      } else if (type == "clevel") {
        //这是 课程等级
        this.indexObj.indexEasy = index;
        this.queryParams.entity.courseLevel =
          object && object.code ? object.code : "";
        this.queryCourse(this.queryParams);
      }
    },
    // 综合按钮
    handleZonghe() {
      // console.log(12);
      this.active = !this.active; // 按钮样式
      this.active2 = false;
      this.active3 = false;
      let queryParams = {
        pageNum: 1,
        pageSize: 12,
        entity: {}, //不传参为默认全部
      };
      this.priceSortBy = "";
      this.isFreeOrIsMember = ""; // 免费课，会员课
      this.queryCourse(queryParams); //请求课程
    },
    // 最新课程
    handleCourse() {
      this.active = false; // 按钮样式
      this.active2 = !this.active2;
      this.active3 = false;
      let queryParams = {
        pageNum: 1,
        pageSize: 12,
        entity: {
          sortBy: "time-desc",
        },
      };
      this.priceSortBy = "";
      this.isFreeOrIsMember = ""; // 免费课，会员课
      this.queryCourse(queryParams); //请求课程
    },
    // 最多购买
    mostBuy() {
      this.active = false; // 按钮样式
      this.active2 = false;
      this.active3 = !this.active3;
      let queryParams = {
        pageNum: 1,
        pageSize: 12,
        entity: {
          sortBy: "purchase-desc",
        },
      };
      this.priceSortBy = "";
      this.isFreeOrIsMember = ""; // 免费课，会员课
      this.queryCourse(queryParams); //请求课程
    },
    // 价格
    handlePrice() {
      let queryParams = {
        pageNum: 1,
        pageSize: 12,
        entity: {
          sortBy: "",
        },
      };
      if (this.priceSortBy === "1" || this.priceSortBy === "") {
        this.active = false; // 按钮样式
        this.active2 = false;
        this.active3 = false;
        this.priceSortBy = "2";
        this.isFreeOrIsMember = "";
        queryParams.entity.sortBy = "price-asc";
        this.queryCourse(queryParams);
      } else if (this.priceSortBy === "2") {
        this.active = false; // 按钮样式
        this.active2 = false;
        this.active3 = false;
        this.priceSortBy = "1";
        this.isFreeOrIsMember = "";
        queryParams.entity.sortBy = "price-desc";
        this.queryCourse(queryParams);
      }
    },
    // 免费课程/会员课程
    changeFreeOrMember(e) {
      // e就是1 ，或者2
      // let queryParams = {
      //   pageNum: 1,
      //   pageSize: 12,
      //   entity: {
      //     sortBy: ''
      //   }
      // }
      if (e === "2") {
        this.active = false; // 按钮样式
        this.active2 = false;
        this.active3 = false;
        this.priceSortBy = "";
        this.queryParams.entity.isFree = "1";
        this.queryParams.entity.isMember = "";
        this.queryCourse(this.queryParams);
      } else if (e === "1") {
        this.active = false; // 按钮样式
        this.active2 = false;
        this.active3 = false;
        this.priceSortBy = "";
        this.queryParams.entity.isFree = "";
        this.queryParams.entity.isMember = "1";
        this.queryCourse(this.queryParams);
      }
    },
    // 分页器
    getList() {
      queryCourse(this.queryParams).then((res) => {
        // console.log(res);
        this.totalPage = res.data.pageInfo.total;
      });
    },
    // 加入购物车
    accCart(item) {
      createToken().then(res=>{
        // console.log(res);  
        this.tokens = res.data.token
        addShopCar({
          courseId:item.id,
          memberId:this.userInfo.id,
          token:this.tokens
        }).then(res=>{
          console.log(res,123);
        })
      })
    }, 
  },
};
</script>


<style scoped>
.all .active,
.all .active2,
.all .active3 {
  color: #2c80ff;
}

.all .split {
  color: #d2d2d2;
}

/* 分类开始 */
.course-main {
  padding: 20px 0;
  width: 100%;
  height: 130px;
  background: #f3f5f9;
}

.search-container {
  width: 1200px;
  margin: 0 auto;
  position: relative;
  height: 100%;
}

.search-item {
  display: flex;
  overflow: hidden;
  cursor: pointer;
  position: absolute;
  height: 45px;
  transition: all 0.5s;
}

.search-item-transition:hover {
  z-index: 777;
  height: auto;
  box-shadow: rgb(95 101 105 / 10%) 0px 12px 20px 0px;
  border-radius: 8px;
  background: rgba(255, 255, 255);
}

.search-item .title-name {
  width: 100px;
  font-size: 16px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  line-height: 25px;
  text-align: justify;
  color: #333333;
  padding: 10px;
  opacity: 1;
}

.search-item .title-name:after {
  content: ".";
  width: 100%;
  display: inline-block;
  overflow: hidden;
  height: 0;
}

.search-item .all-items {
  width: calc(100% - 120px);
  min-height: 25px;
  display: flex;
  flex-wrap: wrap;
}

.title .all-list {
  width: 40px;
  height: 25px;
  line-height: 25px;
  border-radius: 4px;
  padding: 0 10px;
  align-items: center;
  text-align: center;
}

.title .all {
  opacity: 1;
  color: #2c80ff;
}

.title .item {
  height: 25px;
  line-height: 25px;
  margin: 0 15px;
  font-size: 16px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  line-height: 21px;
  /* color: #515759; */
  opacity: 1;
}

.title .item .active {
  color: #2c80ff;
}

.category-poniter {
  height: 25px;
  line-height: 25px;
  margin: 10px 5px;
  cursor: pointer;
  border: none !important;
  background: rgba(44, 128, 255, 0.1);
  color: #2c80ff !important;
}

.category-poniter-item {
  background: none;
  color: rgba(81, 87, 89, 1) !important;
}

/* 分类结束 */

/* 搜索条件开始 */
.coursemain {
  width: 100%;
}

.main-container {
  width: 1200px;
  /*height: 100%;*/
  margin: 0 auto;
  /* background: chartreuse; */
}

.container-top {
  display: flex;
  justify-content: space-between;
  margin-top: 12px;
}

.all {
  display: flex;
  padding-top: 20px;
  font-size: 16px;
  color: #515759;
}

.all .item:first-child {
  margin-right: 20px;
}

.all .item {
  margin: 0 10px;
  cursor: pointer;
}

.right {
  display: flex;
  padding-top: 20px;
  font-size: 16px;
  color: #515759;
}

.right .right-item {
  margin-left: 10px;
}

.right .right-items {
  margin-right: 0px;
}

.arrow {
  position: relative;
}

.arrow i:first-child {
  position: absolute;
  top: -1px;
}

.arrow i:last-child {
  position: absolute;
  top: 7px;
}

.check {
  width: 15px;
  height: 15px;
  cursor: pointer;
}

.up {
  position: absolute;
  top: 5px;
  left: 2px;
}

.down {
  position: absolute;
  top: 15px;
  left: 2px;
  transform: rotate(180deg);
  -ms-transform: rotate(180deg);
  /* IE 9 */
  -moz-transform: rotate(180deg);
  /* Firefox */
  -webkit-transform: rotate(180deg);
  /* Safari 和 Chrome */
  -o-transform: rotate(180deg);
  /* Opera */
}

/* 搜索调价结束 */
/* 课程内容开始 */
.newCourseContent {
  width: 1200px;
  margin: 30px auto 0px auto;
}

.newCourseContent .courseUl {
  display: flex;
  flex-wrap: wrap;
}

.newCourseContent .courseUl .courseItem {
  width: 285px;
  height: 280px;
  margin: 0 20px 20px 0;
}

.newCourseContent .courseUl .courseItem:hover {
  cursor: pointer;
}

.newCourseContent .courseUl .courseItem:nth-child(4n + 0) {
  margin-right: 0 !important;
}

.courseCard {
  width: 1200px;
  height: 600px;
  margin: 20px 0 0 0;
}

.courseInfo {
  position: relative;
  width: 100%;
  height: 260px;
  background: #ffffff;
  box-shadow: 2px 4px 4px rgba(27, 39, 94, 0.1);
  opacity: 1;
  overflow: hidden;
  border-radius: 8px;
  transition: margin-top 0.2s;
  -webkit-transition: margin-top 0.2s;
}

.courseInfo:hover {
  margin-top: -10px;
}

.courseBg {
  position: relative;
  width: 100%;
  height: 160px;
}

.courseImg {
  width: 100%;
  height: 100%;
}

.courseDesc {
  position: absolute;
  top: 45px;
  left: 15px;
  font-size: 24px;
  color: #ffffff;
}

.courseName {
  margin: 10px;
  font-weight: bold;
  font-size: 14px;
  color: #333333;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.courseDegree {
  margin-left: 10px;
  font-size: 12px;
  color: #808080;
}

.coursePrice {
  display: flex;
  font-size: 14px;
  margin: 10px;
  justify-content: space-between;
}

.courseMemberbg {
  position: relative;
  left: 0px;
  top: 2px;
  width: 150px;
  height: 25px;
  color: red;
  font-weight: 700;
  line-height: 25px;
}

.courseMemberbg img {
  width: 15px;
  height: 10px;
  padding-left: 5px;
}

.coursePriceZero {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 72px;
  font-size: 14px;
  font-weight: 700;
  margin-top: 2px;
  padding: 0 1px;
  color: rgba(53, 134, 255, 1);
}

.courseMember {
  padding-left: 15px;
  /*position: absolute;
  line-height: 25px;
  left: 0px;*/
}

.memberlogo {
  position: absolute;
  top: 0;
  right: 0;
  z-index: 999;
  margin: 5px 5px 0 0;
}

.memberlogo img {
  width: 40px;
  height: 20px;
}

.price {
  line-height: 29px;
  left: 90px;
  color: #ff727f;
  font-weight: 700;
}

/* 课程内容结束 */
/* 分页开始 */
.pages {
  width: 100%;
  height: 100%;
  margin: 50px auto !important;
}

.addCart {
  margin-top: 3px;
  color: #ff3d17;
}

/* 分页结束 */
</style>
